from flask import Blueprint, render_template, flash, redirect, url_for, request, current_app
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import create_access_token, jwt_required, create_refresh_token, jwt_refresh_token_required, get_jwt_identity, fresh_jwt_required
from sqlalchemy import or_
from application.users.forms import *
from application.users.models import *
from application import db

# 生成蓝图对象
users = Blueprint('users', __name__)

# 注册
@users.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    # 验证表单
    if form.validate_on_submit():
        users = Users()
        users.name = form.name.data
        password = form.password.data
        # 对密码hash
        password_hash = generate_password_hash(password)
        # 取得前端用户输入的数据，去掉两边的空格
        user_type = form.user_type.data.strip()
        # 给注册用户分配角色
        if user_type is not None:
            if user_type == '3':
                users.user_type = 3
            if user_type == '2':
                users.user_type = 0
            if user_type == '1':
                users.user_type = 1
        else:
            users.user_type = 0
        users.password = password_hash
        users.mobile = form.mobile.data
        db.session.add(users)
        db.session.commit()
        flash('注册成功')
        return render_template('users/register.html', form=form)
    return render_template('users/register.html', form=form)

# 登录
@users.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # 查询用户是否存在
        name = form.name.data
        user = Users.query.filter(or_(Users.name == name, Users.mobile == name)).first()

        if user is None:
            flash('用户名或密码错误')
            return render_template('users/login.html', form=form)
        password = form.password.data
        password_hash = user.password
        if check_password_hash(password_hash, password):
            # 颁发令牌
            jwt_token = create_access_token(identity=name, fresh=True)
            flash('恭喜你，登录成功')
            # 跳转到首页
            res = redirect(url_for('users.index'))
            res.set_cookie('jwt_token', jwt_token, max_age=3600)
            res.set_cookie('user_name', user.name, max_age=3600)
            return res
        else:
            flash('用户名或密码错误')

    return render_template('users/login.html', form=form)

# 登出
@users.route('/logout')
def logout():
    logout_user()
    flash('登出成功')
    # 跳转到首页
    return redirect(url_for('users.index'))


# 展示所有用户(分页显示)
@users.route('/show_all', methods=['GET', 'POST'])
# @login_required
def show_all():
    page = request.args.get('page', 1, type=int)
    pagination = Users.query.order_by(Users.id.desc()).paginate(page, per_page=current_app.config['COUNT_PER_PAGE'], error_out=False)
    users = pagination.items
    print(users)
    print(11)
    return render_template('users/show_all.html', users=users, pagination=pagination)

# 首页
@users.route('/index', methods=['GET'])
def index():
    return render_template('users/index.html')

# 上传作品
@users.route('/upload_avatar/<int:user_id>', methods=['GET'])
def upload_avatar(user_id):
    return render_template('users/upload_avatar.html', user_id=user_id)

